<?php

/*
Plugin Name: The Feature
Plugin URI: http://no.oneslistening.com/160
Author: Yas
Author URI: http://no.oneslistening.com/
Version: 0.9.7
Description: Adds the interface to declare a post a "feature" and the tools to display the data in your template.
*/

function the_feature($display = '1', $random = 'true') {
	global $wpdb, $id;
	
	if(is_single()) $exclude = $id;
		else $exclude = 0;
	
	$request = "SELECT post_id FROM $wpdb->postmeta LEFT OUTER JOIN $wpdb->posts ON ID = post_id WHERE post_status != 'draft' AND meta_key = 'featuretitle' AND post_id != '$exclude' ORDER BY rand() LIMIT $display";
	$posts = $wpdb->get_results($request);
    
	if($posts) {
		foreach($posts as $post) {
			$image = get_featureimage(stripslashes($post->post_id));
			$title = get_featuretitle(stripslashes($post->post_id));
			$desc = get_featuredesc(stripslashes($post->post_id));

			echo '<div class="featureItem">'.$image.'<br/>'.$title.'</div>';			
		}

	} else {
		echo '<strong>No featured posts were found.</strong>';
	}
}


// Use this function as a template tag to display if a post has been designated a feature. Image not included.

function is_feature() {
	if(get_post_custom_values('featuretitle'))
		$img = '<img class="is_feature" src="'.bloginfo('stylesheet_directory').'/images/is_feature.gif" alt="Featured Post" />';
	echo $img;
}


// The Administration Panel function

function feature_panel() {
	global $wpdb;
	
	if($_GET["saved"] == 'true' && isset($_GET["post_id"])) delete_feature_data($_GET["post_id"]);
	
	$query = "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = 'featuretitle' ";
	$posts = $wpdb->get_results($query);

	$class = 'alternate';
    
    echo '<div class="wrap"><h2>Featured Posts</h2>';
    if($_GET["delete"] == 'true') echo '<div style="border-top: 2px solid #c3f990; border-bottom: 2px solid #c3f990; padding: 4px;"><img src="../wp-content/themes/kiwicanvas/includes/the_feature/ok.gif" alt="ok" style="padding: 0 5px;"/><strong>Featured post removed.</strong></div>';
	echo '<p>Each of the posts below has been designated to be a Featured Post. Using this panel you can manage these posts. Note that removing a post from this list will not delete that post. This list may include posts that are not yet published, but this post will <strong>not</strong> be displayed on your site until they are published.</p>';

	if($posts) {
		echo '<table width="100%" cellpadding="3" cellspacing="3"><tr><th>ID</th><th>Title Link</th><th>Image Link</th><th>Description</th><th>Actions</th></tr>';
		
		foreach($posts as $post) {
			echo '<tr class="'.$class.'"><th scope="row">'.$post->post_id.'</th>';
			echo '<form action="'.get_option('siteurl').'/wp-admin/edit.php?page=the_feature.php&delete=true&post_id='.$post->post_id.'" method="post">';
			echo '<td>'.get_featuretitle($post->post_id).'</td>';
			echo '<td>'.get_featureimage($post->post_id).'</td>';
			echo '<td>'.get_featuredesc($post->post_id).'</td>';
			print '<td><p><input name="deletepost" class="button" onclick="return confirm(\'Are you sure you want to remove this post from the Featured list?\')" type="submit" id="deletepost" value="Remove" /></td>';
			echo '</form>';
			echo '</tr>';
			
			if($class == 'alternate') { $class = ''; } else { $class = 'alternate'; }
		}
		
		echo '</table>';

	} else {
		echo '<strong>No featured posts were found.</strong>';
	}

}


// The Post Panel function

function select_the_feature() {
	global $post;

	$postID = $post; 
	if(is_object($post)) $postID = $post->ID; 
	
	//
	// You MUST edit the next line to include the pictures you want
	//
	
	$dir = '../wp-content/themes/kiwicanvas/featurepics/'; // This path is referenced from the WP-ADMIN directory, where the plugin is called.
	
	if (substr($dir,-1) != '/') {
		$dir = $dir.'/';
	}

	$files = scandirectory($dir); // Scans the directory for files.
	
	// Begin Post Panel Interface
	
	?>
	<div id="thefeature" class="dbx-group">
	<fieldset class="dbx-box">
	<h3 class="dbx-handle">Make This Post a Feature</h3>
	<div class="dbx-content">
	<p><input type="checkbox" name="makefeature" id="makefeature" value="1"/> I'd like to make this post a Feature</p>
	<div style="display: none;" id="featureContent">
	<?php
	
	$metadata = has_meta($postID);

	if($metadata) {
		foreach($metadata as $data) {
			if($data['meta_key'] == 'featurepic') {
				$current_pic = $data['meta_value'];
				echo '<input type="hidden" id="feature_image_ID" name="feature_image_ID" value="'.$data['meta_id'].'" />';
			}
			if($data['meta_key'] == 'featuredesc') {
				$current_desc = $data['meta_value'];
				echo '<input type="hidden" id="feature_desc_ID" name="feature_desc_ID" value="'.$data['meta_id'].'" />';
			}
			if($data['meta_key'] == 'featuretitle') {
				$current_title = $data['meta_value'];
				echo '<input type="hidden" id="feature_title_ID" name="feature_title_ID" value="'.$data['meta_id'].'" />';
			}
		}
		if(!isset($current_pic)) $empty = true;
	} else {
		$empty = true;
	}
	?>
	<h4>Click on the image you'd like to use as the Feature preview:</h4>
	
	<div class="featurebox">
	<?php
	
	if($empty) $class = ' selectedFeature';
		else $class = '';
	echo '<a href="javascript:void(0);" onclick="document.post.featurePic.value=\'\'"><img class="featurepic'.$class.'" id="featurepic" src="../wp-content/plugins'.$install_directory.'/the_feature/noimage.gif" /></a>';
	if($files) {
		foreach($files as $file) {
			if(substr($file, -3) == 'jpg' OR substr($file, -3) == 'gif') {
				if(substr($dir,3).$file == $current_pic) $class = ' selectedFeature';
					else $class = '';
				echo '<a href="javascript:void(0);" onclick="document.post.featurePic.value=\''.substr($dir,3).$file.'\'"><img class="featurepic'.$class.'" id="featurepic" src="'.$dir.$file.'" /></a>';
			}
		}
	}

	$limit = 72; // character limit for the description.
	
	?>
	</div>
	<input type="hidden" id="featurePic" name="featurePic" size="40" value="<?php echo $current_pic ?>" />
	Describe this post in one line <small>(Limited to <?php echo $limit ?> characters)</small>:<br/>
	<input type="text" class="text" id="featureDesc" name="featureDesc" size="75" maxlength="<?php echo $limit ?>" value="<?php $description ?>" />
	</div>
	</div>
	</fieldset>
	</div>
	<?php
}

// Saves the data to the wp_postmeta table of your Wordpress database.

function save_feature_data($post_id) {
	if($_POST['featurePic'] == '') return;
	if(isset($_POST['makefeature'])) {
		global $wpdb;

		$metakey[1] = 'featurepic';
		$metavalue[1] = $_POST['featurePic'];
		$meta_image_ID[1] = $_POST['feature_image_ID'];

		$metakey[2] = 'featuredesc';
		$metavalue[2] = $_POST['featureDesc'];
		$meta_image_ID[2] = $_POST['feature_desc_ID'];

		$metakey[3] = 'featuretitle';
		$metavalue[3] = $_POST['post_title'];
		$meta_image_ID[3] = $_POST['feature_title_ID'];

		for($i = 1; $i <= 3; $i++) {
			if($metavalue[$i] != 'null' && $metavalue[$i] != '') {
				if(!$wpdb->query("SELECT meta_value FROM $wpdb->postmeta WHERE post_id = '$post_id' AND meta_key = 'featuretitle'")) {
					$result = $wpdb->query("
						INSERT INTO $wpdb->postmeta 
						(post_id,meta_key,meta_value) 
						VALUES ('$post_id','$metakey[$i]','$metavalue[$i]')
					");

					flush($result);
				}
				if($wpdb->query("SELECT meta_value FROM $wpdb->postmeta WHERE post_id = '$post_id' AND meta_key = 'featuretitle'")) {			
					if(empty($meta_image_ID[$i])) return 'Feature cannot be saved.';
					$result = $wpdb->query("
						UPDATE $wpdb->postmeta 
						SET meta_key = '$metakey[$i]', meta_value = '$metavalue[$i]' 
						WHERE meta_id = '$meta_image_ID[$i]'
					");

					flush($result);
				}
			}
		}
	}
}

function delete_feature_data($post_id) {
	global $wpdb;
	$wpdb->query("DELETE FROM $wpdb->postmeta WHERE post_id = '$post_id' AND meta_key like 'feature%'");
	
	return;
}

function get_featureimage($post_id) {
	global $wpdb, $post_meta_cache;
	$result = $wpdb->get_results("SELECT meta_value FROM $wpdb->postmeta WHERE post_id = '$post_id' AND meta_key = 'featurepic' ");
	
	return '<a href="'.get_permalink($post_id).'"><img class="featureimage" src="'.get_option("siteurl").'/'.$result[0]->meta_value.'" alt="Feature"/></a>';	
}

function get_featuredesc($post_id) {
	global $wpdb, $post_meta_cache;
	$result = $wpdb->get_results("SELECT meta_value FROM $wpdb->postmeta WHERE post_id = '$post_id' AND meta_key = 'featuredesc' ");
	
	return $result[0]->meta_value;
}

function get_featuretitle($post_id) {
	global $wpdb;
	$result = $wpdb->get_results("SELECT meta_value FROM $wpdb->postmeta WHERE post_id = '$post_id' AND meta_key = 'featuretitle' ");

	return '<a href="'.get_permalink($post_id).'">'.$result[0]->meta_value.'</a>';
}

function add_feature_page() { 
	add_management_page('The Feature Options', 'Featured Posts', 8, basename(__FILE__), 'feature_panel');
}

function add_feature_head() { 
	if(strpos($_SERVER['REQUEST_URI'], 'post.php') || strpos($_SERVER['REQUEST_URI'], 'page-new.php')) : ?>
	<link rel="stylesheet" href="<?php bloginfo('siteurl') ?>/wp-content/themes/kiwicanvas/includes/the_feature/css/feature.css" type="text/css" media="screen" />
	<script language="JavaScript" type="text/javascript" src="<?php bloginfo('siteurl')?>/wp-content/themes/kiwicanvas/includes/the_feature/js/prototype.js"></script>
	<script language="JavaScript" type="text/javascript" src="<?php bloginfo('siteurl')?>/wp-content/themes/kiwicanvas/includes/the_feature/js/scriptaculous.js"></script>
	<script language="JavaScript" type="text/javascript" src="<?php bloginfo('siteurl')?>/wp-content/themes/kiwicanvas/includes/the_feature/js/feature.js"></script>
<?php endif;
}

// Hooks and actions
add_action('admin_menu', 'add_feature_page');
add_action('admin_head', 'add_feature_head');
add_action('edit_form_advanced', 'select_the_feature');
add_action('edit_page_form', 'select_the_feature');
add_action('wp_insert_post','save_feature_data');


// Scans the directory (included for PHP 4 users)
if(!function_exists(scandirectory)) {
	function scandirectory($dir = './', $sort = 0) {
		$dir_open = @opendir($dir);
		if (!$dir_open)	return false;
	
		while (($dir_content = readdir($dir_open)) !== false) {
			$files[] = $dir_content;
		}
		if ($sort == 1) rsort($files, SORT_STRING);
			else sort($files, SORT_STRING);
		return $files;
	}
}
?>